﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CoffeeTeaTrading.Core.Infrastructure.Utils;
using CoffeeTeaTrading.UI.Infrastructure.ModelsConstants;
using Cryptography.Configuration;
using Cryptography.Interfaces;
using Cryptography.Managers;
using CoffeeTeaTrading.Core.Entities;

namespace CoffeeTeaTrading.UI.Controllers
{
    public class CartController : Controller
    {
        //
        // GET: /Cart/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult AddToCart()
        {
            var httpCookie = Request.Cookies[CoffeeTeaConsts.ShoppingCart];
            if (httpCookie != null)
            {
                ICryptographyManager crypto = new CryptographyManager(CryptoConfig.CryptoKey, CryptoConfig.CryptoVector);
                var cookiesValue = crypto.Decrypt(httpCookie.Value);
                var cartList = XmlUtils<List<CartItem>>.Deserialize(cookiesValue);
                cartList.Add(new CartItem(){ Count = 1, ProductId = 1});
                cookiesValue = XmlUtils<List<CartItem>>.Serialize(cartList);
                httpCookie.Value = crypto.Encrypt(cookiesValue);

                Response.Cookies.Add(httpCookie);
            }
            else
            {
                ICryptographyManager crypto = new CryptographyManager(CryptoConfig.CryptoKey, CryptoConfig.CryptoVector);
                var cartList = new List<CartItem>();
                cartList.Add(new CartItem() { Count = 1, ProductId = 1 });
                var cookiesValue = XmlUtils<List<CartItem>>.Serialize(cartList);
                var cookie = new HttpCookie(CoffeeTeaConsts.ShoppingCart);
                cookie.Value = crypto.Encrypt(cookiesValue);
                Response.Cookies.Add(cookie);
            }

            return new EmptyResult();
        }
    }
}
